﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Reflection;

namespace My.Common.Helper.JqGrid
{
    public class ModelHelper : IModelHelper
    {
        public string GetPropertyNameOfEntityByDisplayName<T>(string displayName)
        {
            var property = GetPropertyOfEntityByDisplayName<T>(displayName);
            if (property != null)
            {
                return property.Name;
            }

            return string.Empty;
        }

        public Type GetPropertyType(Type modelType, string propertyName)
        {
            return modelType.GetProperty(propertyName).PropertyType;
        }

        private PropertyInfo GetPropertyOfEntityByDisplayName<T>(string displayName)
        {
            var propertyList = typeof(T).GetProperties();
            foreach (var item in propertyList)
            {
                if (item.Name == displayName)
                {
                    return item;
                }

                var customAttrList = item.GetCustomAttributes(false);
                var customAttr = customAttrList.Where(x => x.GetType() == typeof(DisplayNameAttribute))
                    .Select(x => (DisplayNameAttribute)x)
                    .FirstOrDefault(x => x.DisplayName == displayName);
                if (customAttr != null)
                {
                    return item;
                }
            }

            return null;
        }
    }
}